<template>
  <div class="delivery-container">
    <el-card class="delivery-card">
      <h2>Delivery Management</h2>
      
      <!-- Delivery Statistics -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <h3>{{ deliveryStats.pendingShipments || 0 }}</h3>
              <p>Pending Shipments</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <h3>{{ deliveryStats.outForDelivery || 0 }}</h3>
              <p>Out for Delivery</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <h3>{{ deliveryStats.deliveredToday || 0 }}</h3>
              <p>Delivered Today</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <h3>{{ deliveryStats.pickupReady || 0 }}</h3>
              <p>Pickup Ready</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- Search and Filter -->
      <div class="filter-section">
        <el-input 
          v-model="searchQuery" 
          placeholder="Search deliveries (order number, customer)..." 
          prefix-icon="Search"
          style="max-width: 300px; margin-right: 15px;"
        />
        <el-select v-model="filterStatus" placeholder="Filter by status" style="max-width: 200px;">
          <el-option label="All" value=""></el-option>
          <el-option label="Ready to Ship" value="READY_TO_SHIP"></el-option>
          <el-option label="Shipped" value="SHIPPED"></el-option>
          <el-option label="Out for Delivery" value="OUT_FOR_DELIVERY"></el-option>
          <el-option label="Delivered" value="DELIVERED"></el-option>
          <el-option label="Pickup Ready" value="PICKUP_READY"></el-option>
          <el-option label="Pickup Completed" value="PICKUP_COMPLETED"></el-option>
        </el-select>
      </div>
      
      <!-- Delivery Table -->
      <el-table 
        :data="filteredDeliveries" 
        style="width: 100%; margin-top: 20px;" 
        v-loading="loading"
      >
        <el-table-column prop="orderNumber" label="Order Number" width="150"></el-table-column>
        <el-table-column prop="customerName" label="Customer" width="150"></el-table-column>
        <el-table-column prop="deliveryType" label="Type" width="120">
          <template #default="scope">
            {{ scope.row.deliveryType === 'SHIP' ? 'Shipping' : 'Pickup' }}
          </template>
        </el-table-column>
        <el-table-column prop="deliveryStatus" label="Status" width="150">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row.deliveryStatus)" 
              disable-transitions
            >
              {{ scope.row.deliveryStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="estimatedDelivery" label="Est. Delivery" width="150"></el-table-column>
        <el-table-column label="Actions" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewDeliveryDetails(scope.row)">View</el-button>
            <el-dropdown trigger="click" @command="handleStatusChange(scope.row, $event)">
              <el-button size="small" type="primary">
                Update <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="READY_TO_SHIP" v-if="isStatusChangeAllowed(scope.row.deliveryStatus, 'READY_TO_SHIP')">
                    Ready to Ship
                  </el-dropdown-item>
                  <el-dropdown-item command="SHIPPED" v-if="isStatusChangeAllowed(scope.row.deliveryStatus, 'SHIPPED')">
                    Shipped
                  </el-dropdown-item>
                  <el-dropdown-item command="OUT_FOR_DELIVERY" v-if="isStatusChangeAllowed(scope.row.deliveryStatus, 'OUT_FOR_DELIVERY')">
                    Out for Delivery
                  </el-dropdown-item>
                  <el-dropdown-item command="DELIVERED" v-if="isStatusChangeAllowed(scope.row.deliveryStatus, 'DELIVERED')">
                    Delivered
                  </el-dropdown-item>
                  <el-dropdown-item command="PICKUP_READY" v-if="isStatusChangeAllowed(scope.row.deliveryStatus, 'PICKUP_READY')">
                    Ready for Pickup
                  </el-dropdown-item>
                  <el-dropdown-item command="PICKUP_COMPLETED" v-if="isStatusChangeAllowed(scope.row.deliveryStatus, 'PICKUP_COMPLETED')">
                    Pickup Completed
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div class="pagination-section">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredDeliveries.length"
        />
      </div>
    </el-card>
    
    <!-- Delivery Details Dialog -->
    <el-dialog title="Delivery Details" v-model="detailsDialogVisible" width="800px">
      <div v-if="selectedDelivery">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="Order Number" :span="2">
            {{ selectedDelivery.orderNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="Customer Name">
            {{ selectedDelivery.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="Customer Phone">
            {{ selectedDelivery.customerPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="Delivery Type">
            {{ selectedDelivery.deliveryType === 'SHIP' ? 'Shipping' : 'Pickup in Store' }}
          </el-descriptions-item>
          <el-descriptions-item label="Status">
            <el-tag :type="getStatusType(selectedDelivery.deliveryStatus)" disable-transitions>
              {{ selectedDelivery.deliveryStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Estimated Delivery">
            {{ selectedDelivery.estimatedDelivery }}
          </el-descriptions-item>
          <el-descriptions-item label="Created At" :span="2">
            {{ selectedDelivery.createdAt }}
          </el-descriptions-item>
          <el-descriptions-item label="Delivery Address" v-if="selectedDelivery.deliveryAddress">
            {{ selectedDelivery.deliveryAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="Pickup Location" v-if="selectedDelivery.pickupLocation">
            {{ selectedDelivery.pickupLocation }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- Delivery Timeline -->
        <h3 style="margin-top: 20px;">Delivery Timeline</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(event, index) in deliveryTimeline"
            :key="index"
            :timestamp="event.timestamp"
            :color="getTimelineColor(event.status)"
          >
            <el-card>
              <h4>{{ event.status }}</h4>
              <p v-if="event.location">Location: {{ event.location }}</p>
              <p v-if="event.details">{{ event.details }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
      <template #footer>
        <el-button @click="detailsDialogVisible = false">Close</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, computed } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'

export default {
  name: 'MerchantDelivery',
  setup() {
    const loading = ref(false)
    const detailsDialogVisible = ref(false)
    const selectedDelivery = ref(null)
    
    const searchQuery = ref('')
    const filterStatus = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // Mock data for deliveries
    const deliveries = ref([
      {
        orderNumber: 'ORD12345678',
        customerName: 'John Doe',
        customerPhone: '123-456-7890',
        deliveryType: 'SHIP',
        deliveryStatus: 'DELIVERED',
        estimatedDelivery: '2023-10-18',
        createdAt: '2023-10-15 14:30',
        deliveryAddress: '123 Main St, City, State 12345',
        pickupLocation: null
      },
      {
        orderNumber: 'ORD12345679',
        customerName: 'Jane Smith',
        customerPhone: '098-765-4321',
        deliveryType: 'SHIP',
        deliveryStatus: 'OUT_FOR_DELIVERY',
        estimatedDelivery: '2023-10-17',
        createdAt: '2023-10-16 10:15',
        deliveryAddress: '456 Oak Ave, Town, State 54321',
        pickupLocation: null
      },
      {
        orderNumber: 'ORD12345680',
        customerName: 'Bob Johnson',
        customerPhone: '555-123-4567',
        deliveryType: 'PICKUP',
        deliveryStatus: 'PICKUP_READY',
        estimatedDelivery: 'Ready for pickup',
        createdAt: '2023-10-16 16:45',
        deliveryAddress: null,
        pickupLocation: 'Main Store - 789 Broadway, New York, NY'
      }
    ])
    
    // Mock delivery statistics
    const deliveryStats = {
      pendingShipments: 5,
      outForDelivery: 3,
      deliveredToday: 12,
      pickupReady: 7
    }
    
    const filteredDeliveries = computed(() => {
      let result = deliveries.value
      
      // Apply search filter
      if (searchQuery.value) {
        result = result.filter(delivery => 
          delivery.orderNumber.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
          delivery.customerName.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }
      
      // Apply status filter
      if (filterStatus.value) {
        result = result.filter(delivery => delivery.deliveryStatus === filterStatus.value)
      }
      
      // Apply pagination
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return result.slice(start, end)
    })
    
    const viewDeliveryDetails = (delivery) => {
      selectedDelivery.value = delivery
      // Generate mock timeline based on delivery status
      deliveryTimeline.value = generateTimelineForDelivery(delivery)
      detailsDialogVisible.value = true
    }
    
    const handleStatusChange = (delivery, newStatus) => {
      ElMessageBox.confirm(
        `Are you sure you want to update the delivery status to ${newStatus}?`,
        'Confirm Status Change',
        {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      ).then(() => {
        // In a real application, you would make an API call to update the delivery status
        // For now, updating the mock data
        delivery.deliveryStatus = newStatus
        ElMessage.success(`Delivery status updated to ${newStatus}`)
      }).catch(() => {
        // User cancelled
      })
    }
    
    const isStatusChangeAllowed = (currentStatus, newStatus) => {
      // Define valid status transitions
      const validTransitions = {
        'READY_TO_SHIP': ['SHIPPED'],
        'SHIPPED': ['OUT_FOR_DELIVERY'],
        'OUT_FOR_DELIVERY': ['DELIVERED'],
        'DELIVERED': [],
        'PICKUP_READY': ['PICKUP_COMPLETED'],
        'PICKUP_COMPLETED': []
      }
      
      const allowed = validTransitions[currentStatus] || []
      return allowed.includes(newStatus)
    }
    
    const getStatusType = (status) => {
      switch (status) {
        case 'READY_TO_SHIP': return 'warning'
        case 'SHIPPED': return 'primary'
        case 'OUT_FOR_DELIVERY': return 'danger'
        case 'DELIVERED': return 'success'
        case 'PICKUP_READY': return 'primary'
        case 'PICKUP_COMPLETED': return 'success'
        default: return 'info'
      }
    }
    
    const getTimelineColor = (status) => {
      switch (status) {
        case 'Ready to Ship': return '#E6A23C'
        case 'Shipped': return '#409EFF'
        case 'Out for Delivery': return '#F56C6C'
        case 'Delivered': return '#67C23A'
        case 'Ready for Pickup': return '#409EFF'
        case 'Pickup Completed': return '#67C23A'
        default: return '#909399'
      }
    }
    
    // Mock timeline for delivery details
    const deliveryTimeline = ref([])
    
    const generateTimelineForDelivery = (delivery) => {
      // Mock timeline based on delivery status
      if (delivery.deliveryType === 'SHIP') {
        return [
          {
            status: 'Order Placed',
            timestamp: delivery.createdAt,
            details: 'Your order has been placed'
          },
          {
            status: 'Ready to Ship',
            timestamp: '2023-10-16 09:00',
            location: 'Warehouse A',
            details: 'Package is being prepared for shipping'
          },
          {
            status: 'Shipped',
            timestamp: '2023-10-16 14:30',
            location: 'Main Distribution Center',
            details: 'Your package has been shipped'
          },
          {
            status: delivery.deliveryStatus,
            timestamp: '2023-10-17 10:00',
            location: delivery.deliveryStatus === 'DELIVERED' ? 'Customer Address' : 'Local Delivery Hub',
            details: delivery.deliveryStatus === 'DELIVERED' 
              ? 'Package delivered to customer' 
              : 'Package out for delivery today'
          }
        ]
      } else {
        // For pickup orders
        return [
          {
            status: 'Order Placed',
            timestamp: delivery.createdAt,
            details: 'Your order has been placed for pickup'
          },
          {
            status: 'Ready for Pickup',
            timestamp: '2023-10-17 09:00',
            location: delivery.pickupLocation,
            details: 'Your order is ready for pickup'
          },
          {
            status: delivery.deliveryStatus,
            timestamp: delivery.deliveryStatus === 'PICKUP_COMPLETED' ? '2023-10-17 14:00' : '',
            location: delivery.pickupLocation,
            details: delivery.deliveryStatus === 'PICKUP_COMPLETED' 
              ? 'Order picked up by customer' 
              : 'Order ready for pickup at store'
          }
        ]
      }
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    return {
      loading,
      detailsDialogVisible,
      selectedDelivery,
      searchQuery,
      filterStatus,
      currentPage,
      pageSize,
      deliveries,
      deliveryStats,
      filteredDeliveries,
      viewDeliveryDetails,
      handleStatusChange,
      isStatusChangeAllowed,
      getStatusType,
      getTimelineColor,
      deliveryTimeline,
      handleSizeChange,
      handleCurrentChange,
      ArrowDown
    }
  }
}
</script>

<style scoped>
.delivery-container {
  padding: 20px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.delivery-card {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-item h3 {
  margin: 0 0 5px 0;
  font-size: 24px;
  color: #409EFF;
}

.stat-item p {
  margin: 0;
  color: #909399;
}

.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.pagination-section {
  margin-top: 20px;
  text-align: center;
}
</style>